# -*- coding: utf-8 -*-
# @Date     : 2021/3/8 15:16
# @Author   : xiaochuang.wu
# @File     : __init__.py.py


import aioredis, logging
from peewee import Proxy
from peewee_async import PooledMySQLDatabase, Manager
logger = logging.getLogger("root")

db_proxy = Proxy()


class _Mask: pass


class ServerSetup(object):
    """此类用于Sanic 服务启动前后的钩子操作, 可以继承或者重写 在app.py中register_listener指定自定义的钩子函数"""
    @staticmethod
    async def init_all(app, loop=None, use_db=True, use_redis=True):
        if use_db:
            ServerSetup.db_setup(app, loop)
        if use_redis:
            await ServerSetup.cache_setup(app, loop)

    @staticmethod
    def db_setup(app, loop=None):
        # init db_proxy
        _max_connection = app.config.MAX_DB_CONNECTION if hasattr(app.config, "MAX_DB_CONNECTION") else 20
        _db_conf = app.config.DB_CONF
        _database = PooledMySQLDatabase(max_connections=_max_connection, **_db_conf)
        db_proxy.initialize(_database)
        app.ctx.db = _database
        app.ctx.db_manager = Manager(db_proxy)

        # create tables on db
        # db_proxy.create_tables(models, safe=True)

    @staticmethod
    async def cache_setup(app, loop=None):
        _conf = app.config.REDIS_CONF
        _t = (_conf['host'], _conf['port'])
        app.ctx.aio_cli = await aioredis.create_redis_pool(_t, password=_conf['password'], encoding="utf-8", db=_conf['db'], loop=loop)

    @staticmethod
    async def close_all(app, loop):
        # close db connection
        if hasattr(app.ctx, 'db_manager'):
            await app.ctx.db_manager.close()
        if hasattr(app.ctx, 'db'):
            await app.ctx.db.close_async()

        # close redis connection
        if hasattr(app.ctx, 'aio_cli'):
            app.ctx.aio_cli.close()
            await app.ctx.aio_cli.wait_closed()
